﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SignInServer.Server.Tools;

namespace SignInServer.Server
{
    /// <summary>
    /// 基础消息包
    /// </summary>
    class BasicMessage
    {
        private int messageType;
        private byte[] mainData;

        public BasicMessage()
        {

        }

        public BasicMessage(int messageType, byte[] mainData)
        {
            this.messageType = messageType; this.mainData = mainData;
        }
        /// <summary>
        /// 获取该数据包的主体数据
        /// </summary>
        /// <returns></returns>
        public byte[] getMainData()
        {
            return mainData;
        }
        /// <summary>
        /// 获取该数据包的类别
        /// </summary>
        /// <returns></returns>
        public int getMessageType()
        {
            return messageType;
        }
        /// <summary>
        /// 获取该消息包的列表的bytes形式
        /// </summary>
        /// <returns></returns>
        public byte[] getMessageTypeBytes()
        {
            return ConvertTypeTool.Int32ToByteArray(messageType);
        }
        /// <summary>
        /// 获取主体数据大小
        /// </summary>
        /// <returns></returns>
        public int getMainDataSize()
        {
            return mainData.Length;
        }
        /// <summary>
        /// 获取该消息包的byte[]形式
        /// </summary>
        /// <returns></returns>
        public byte[] generatedMessage()
        {
            return ConvertTypeTool.PooledByteArray(getMessageTypeBytes(), mainData);
        }
        /// <summary>
        /// 拆分单个消息包(仅含有dataType和mainData)，得到请求id及数据主体
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static BasicMessage disassembleMessage(byte[] msg)
        {
            byte[] typeString = msg.Take(4).ToArray();
            int typeInt = ConvertTypeTool.ByteArrayToInt32(typeString);
            byte[] dataBytes = msg.Skip(4).ToArray();
            return new BasicMessage(typeInt, dataBytes);
        }
        /// <summary>
        /// 合成单个数据包，得到消息包的byte[]形式
        /// </summary>
        /// <param name="basicMessage"></param>
        /// <returns></returns>
        public static byte[] generatedMessage(BasicMessage basicMessage)
        {
            return ConvertTypeTool.PooledByteArray(basicMessage.getMessageTypeBytes(), basicMessage.getMainData());
        }
        /// <summary>
        /// 合成单个数据包，得到消息包的byte[]形式
        /// </summary>
        /// <param name="type"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] generatedMessage(int type, byte[] data)
        {
            return ConvertTypeTool.PooledByteArray(ConvertTypeTool.Int32ToByteArray(type), data);
        }
    }
}
